package com.qzd.prototype.deep;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 深克隆:全克隆
 */
public class ConcretePrototy implements Cloneable,Serializable {
    private String name;
    private int age;
    private List<String> slist=new ArrayList<String>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public List<String> getSlist() {
        return slist;
    }

    public void setSlist(List<String> slist) {
        this.slist = slist;
    }

    @Override
    public String toString() {
        return "ConcretePrototy{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", slist=" + slist +
                '}';
    }
    //浅克隆
    public ConcretePrototy clone() {
        try {
            return (ConcretePrototy) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过序列化进行深克隆
     * @return
     */
    public ConcretePrototy deepclone()throws Exception{
        //创建一个缓冲输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream obs = new ObjectOutputStream(out);
        //把对象写入流
        obs.writeObject(this);
        ByteArrayInputStream input = new ByteArrayInputStream(out.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(input);
        return (ConcretePrototy) ois.readObject();
    }
    /**
     * 深克隆公共方法
     *
     */
    public static <T extends Serializable> T clone(T t) {
        T cloneObj = null;
        ObjectOutputStream obs = null;
        ObjectInputStream ois = null;
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            obs = new ObjectOutputStream(out);
            //把对象写入流
            obs.writeObject(t);
            ByteArrayInputStream input = new ByteArrayInputStream(out.toByteArray());
            ois = new ObjectInputStream(input);
            cloneObj = (T) ois.readObject();
            obs.close();
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cloneObj;
    }
}
